package com.lsh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsh.dao.UserMapper;
import com.lsh.pojo.LoginTicket;
import com.lsh.pojo.User;
import com.lsh.service.IUserService;
import com.lsh.utils.CommunityUtil;
import com.lsh.utils.HostHolder;
import com.lsh.utils.MailUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 刘书豪
 * @since 2022-07-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private UserMapper userMapper;
    @Autowired
    private TemplateEngine templateEngine;
    @Resource
    private MailUtil mailUtil;
    @Autowired
    private LoginTicketServiceImpl loginTicketService;
    @Resource
    private HostHolder hostHolder;
    @Override
    public User getById(Serializable id) {
        return super.getById(id);
    }
    @Override
    public User selectByName(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public List<User> list() {
        return super.list();
    }

    public Map<String, Object> register(User user) {
        Map<String, Object> map = new HashMap<>();
        // 空值处理
        if (user == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }
        if (StringUtils.isBlank(user.getUsername())) {
            map.put("usernameMsg", "账号不能为空!");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword())) {
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空!");
            return map;
        }
        // 验证账号
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",user.getUsername());
        User user1 = userMapper.selectOne(wrapper);
        if (user1 != null) {
            map.put("usernameMsg", "该账号已存在!");
            return map;
        }
        // 验证邮箱
        QueryWrapper<User> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("email",user.getEmail());
        User user2 = userMapper.selectOne(wrapper1);
        if (user2 != null) {
            map.put("emailMsg", "该邮箱已被注册!");
            return map;
        }
        // 注册用户
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));
        user.setType(0);
        user.setStatus(0);
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        user.setCreateTime(LocalDateTime.now());
        userMapper.insert(user);
        // 激活邮件
        Context context = new Context();
        context.setVariable("email", user.getEmail());
        // http://localhost:8080/activation/101/code
        String url = "http://localhost:8080"+ "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url", url);
        String content = templateEngine.process("/mail/activation", context);
        mailUtil.sendMail(user.getEmail(), "激活账号", content);
        return map;
    }
    //实现激活验证
    public int activation(int userId, String code) {
        User user = userMapper.selectById(userId);
        if (user.getStatus() == 1) {
            return 0;
        } else if (user.getActivationCode().equals(code)) {
            user.setStatus(1);
            userMapper.updateById(user);
            return 1;
        } else {
            return 2;
        }
    }

    public LoginTicket getTicket(String ticket){
        return loginTicketService.getTicketByTicket(ticket);
    }
    @Override
    public Map<String, Object> login(String username, String password, int dateTime) {
        Map<String,Object> map = new HashMap<>();
        // 验证账号
        User user = selectByName(username);
        if (user == null) {
            map.put("usernameMsg", "该账号不存在!");
            return map;
        }
        // 验证状态
        if (user.getStatus() == 0) {
            map.put("usernameMsg", "该账号未激活!");
            return map;
        }
        // 验证密码
        password = CommunityUtil.md5(password + user.getSalt());
        if (!user.getPassword().equals(password)) {
            map.put("passwordMsg", "密码不正确!");
            return map;
        }
        // 生成登录凭证
        LoginTicket ticketByUserId = loginTicketService.getTicketByUserId(user.getId());
        if(ticketByUserId==null){
            LoginTicket loginTicket = new LoginTicket();
            loginTicket.setUserId(user.getId());
            loginTicket.setTicket(CommunityUtil.generateUUID());
            loginTicket.setStatus(0);
            LocalDateTime dateTime1 = LocalDateTime.now();
            loginTicket.setExpired(dateTime1.plusDays(dateTime));
            loginTicketService.insert(loginTicket);
            map.put("ticket", loginTicket.getTicket());
        }else {
            ticketByUserId.setTicket(CommunityUtil.generateUUID());
            ticketByUserId.setStatus(0);
            LocalDateTime dateTime1 = LocalDateTime.now();
            ticketByUserId.setExpired(dateTime1.plusDays(dateTime));
            loginTicketService.updateById(ticketByUserId);
            map.put("ticket",ticketByUserId.getTicket());
        }
        return map;
    }

    @Override
    public Map<String, Object> updatePassword(String oldPassword, String newPassword1,String newPassword2) {
        Map<String,Object> map = new HashMap<>();
        User user = hostHolder.getUser();
        oldPassword = CommunityUtil.md5(oldPassword+user.getSalt());
        if(oldPassword==null){
            map.put("oldPasswordMsg","原密码不能为空");
            return map;
        }
        if(newPassword1 == null){
            map.put("newPasswordMsg","新密码不能为空");
            return map;
        }
        if(!user.getPassword().equals(oldPassword)){
            map.put("oldPasswordMsg","原密码错误");
            return map;
        }
        if(!newPassword1.equals(newPassword2)){
            map.put("newPasswordMsg2","两次输入的密码不一致");
            return map;
        }
        newPassword1 = CommunityUtil.md5(newPassword1+user.getSalt());
        user.setPassword(newPassword1);
        userMapper.updateById(user);
        LoginTicket ticketByUserId = loginTicketService.getTicketByUserId(user.getId());
        logout(ticketByUserId.getTicket());
        map.put("success","修改成功");
        return map;
    }

    public void logout(String ticket){
        LoginTicket loginTicket = loginTicketService.getTicketByTicket(ticket);
        loginTicket.setStatus(1);
        loginTicketService.updateById(loginTicket);
    }
}
